<script setup>
import { reactive, ref } from 'vue'
import easyapi from '../api'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios';

import jwt_decode from 'jwt-decode';
// 解析token中的用户名
const getnameFromToken = (token) => {
  const decoded = jwt_decode(token);
  console.log(decoded); // 打印解码后的对象
  return decoded.username;
};
// 新增方法用于获取验证码
const getCaptcha = async () => {
  try {
    const response = await axios.get('/api/captcha/get', { responseType: 'arraybuffer' });
    const imageUrl = URL.createObjectURL(new Blob([response.data], { type: 'image/jpeg' }));
    captchaImageUrl.value = imageUrl;
  } catch (error) {
    console.error('Error fetching captcha:', error);
  }
};
const router = useRouter()
const formRef = ref({})
const loginObj = ref({})

// 初始化验证码图像 URL
const captchaImageUrl = ref('');

// 刷新验证码
const refreshCaptcha = () => {
  getCaptcha();
};
// 获取验证码
getCaptcha();

// 登录方法
const dologin = async function () {
  formRef.value?.validate(async valid => {
    if (valid) {
      // 添加验证码验证逻辑
      const captchaValid = await checkCaptcha(loginObj.value.captcha);
      if (!captchaValid) {
        ElMessage({
          type: 'error',
          message: '验证码错误'
        });
        refreshCaptcha();
        return;
      }

      let result = await easyapi.postForm('/api/dologin', loginObj.value)
      console.log(result)
      if (result.code === 200 && result.data) {
        sessionStorage.setItem('easytoken', result.data);
        const username = getnameFromToken(result.data);
        sessionStorage.setItem('username', username);
        console.log(username);
        ElMessage({
          type: 'success',
          message: result.message
        })
        setTimeout(() => {
          router.push('/one')
        }, 1000)
      } else {
        ElMessage({
          type: 'error',
          message: '账号或密码错误'
        });
        // 如果登录失败，刷新验证码
        refreshCaptcha();
      }
    } else {
      ElMessage({
        type: 'warning',
        message: '请填入正确的用户名格式'
      });
      // 如果表单验证失败，刷新验证码
      refreshCaptcha();
    }
  })
}

// 验证验证码有效性
const checkCaptcha = async (captcha) => {
  try {
    const response = await axios.get(`/api/captcha/check?captcha=${captcha}`);
    return response.data;
  } catch (error) {
    console.error('Error checking captcha:', error);
    return false;
  }
}


const checkname = function (rule, value, callback) {
  const reg = /^[A-Za-z]\w{2,7}$/
  if (reg.test(loginObj.value.username)) {
    callback()
  } else {
    callback(new Error('输入正确的用户名'))
  }
}

const easyrules = reactive({
  username: [{ validator: checkname, trigger: 'blur' }],
  userpass: [{}],
  captcha: [{}]
})

/**#################################################### */

//新增账号

function ToRegister() {
  router.push('/register'); // 跳转到入住登记页面
}

const addWinsible=ref(false);
const addformRef=ref([]);
const addObject=ref({
  username:'',
  position:''
});
const addrules=reactive({
  username: [
    { required: true, message: '请输入客人姓名', trigger: 'blur' },
    {
      pattern: /^[A-Za-z]\w{2,7}$/,
      message: '账号必须字母开头后面跟2到7个数字',
      trigger: 'blur'
    }],
    userpass:[{ required: true, message: '请输入客人姓名', trigger: 'blur' },],
    position: [{ required: true, message: '请输入客人姓名', trigger: 'blur' },]
})
const oppWinsible=()=>{
  addObject.value={};
  addWinsible=true;
}

// 方法用于关闭弹窗并导航到下一个页面
const addSave = async function() {
  addformRef.value?.validate(async valid => {
    if (valid) {
  const result = await easyapi.postForm('/api/reservationsjson', addObjectTo.value);
    // 表格数据变更
  tableData1.value.unshift(result.data);
  console.log(result);
  ElMessage({
    type: 'success',
    message: '预定成功',
  }), closeAddWinTo();
    } else {
      console.log('表单验证未通过');
      return false;
    }
  });

};
</script>

<template>
  <el-form
    :rules="easyrules"
    ref="formRef"
    :model="loginObj"
  >
    <div class="login-container">

      <div class="login-box">
        <h1 class="title">酒店管理系统</h1>
        <el-form-item label="用户名" label-width="80" prop="username">
          <el-input v-model="loginObj.username" autocomplete="off" prop="username" :style="{ fontSize: '1.5em' }" clearable />
        </el-form-item>
        <br />
        <el-form-item label="密码" label-width="80" prop="userpass">
          <el-input v-model="loginObj.userpass" autocomplete="off"  show-password :style="{ fontSize: '1.5em' }" />
        </el-form-item>
          <!-- 添加验证码显示 -->
        <el-form-item label="验证码" label-width="80">
          <div style="display: flex;">
            <img :src="captchaImageUrl" @click="refreshCaptcha" alt="验证码" style="width: 100px; height: 30px;" />
            <el-input v-model="loginObj.captcha" style="margin-left: 10px;" placeholder="请输入验证码" />
          </div>
        </el-form-item>
        <div class="button-container">
            <el-button type="primary" @click="dologin">登录</el-button>
            <div class="register-link">
              <span>没有账号？</span>
              <a href="#" @click.prevent="ToRegister" class="register-link-text">去注册</a>
            </div>
          </div>
        </div>
      </div>
  </el-form>
</template>


<style scoped>

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url('../image/16.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.login-box {
  background-color: rgba(250, 252, 253, 0.6); /* 半透明蓝色 */
  padding: 60px;
  border-radius: 30px;
  width: 300px; /* 调整宽度以适应内容 */
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

.title {
  color: #2d17d3; /* 更改为深灰色 */
  margin-bottom: 50px;
  text-align: center;
}

.el-input {
  width: 100%;
}

.el-button {
  width: 40%;
  padding: 10px;
  background-color: #508dce;
  color: white;
  border: none;
  border-radius: 10px;
  cursor: pointer;
}

.el-button:hover {
  background-color: #174e89;
}

/* 使用户名和密码输入框的字体更大 */
.el-input__inner {
  font-size: 1.5em;
}

.button-container {
  display: flex;
  justify-content: space-between;
}

.register-link {
  display: flex;
  align-items: center;
}

.register-link-text {
  color: #409eff;
  text-decoration: none;
  cursor: pointer;
}

.register-link-text:hover {
  text-decoration: underline;
}

</style>